<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
	<title>Document</title>
</head>
<body>
	<div id="preview" style="height: 400px; border: 5px solid red;"></div>
	<script type="text/javascript">
	(function() {
		document.addEventListener('paste', function (e) {
		    var items = ((e.clipboardData || window.clipboardData).items) || [];
		    var file = null;

		    if (items && items.length) {
	           for (var i = 0; i < items.length; i++) {
	               if (items[i].type.indexOf('image') !== -1) {
	                   file = items[i].getAsFile();
	                   break;
	               }
	           }
	       }

		    if (!file) {
		        alert('粘贴内容非图片！');
		        return;
		    }

		    var reader = new FileReader()
		    reader.onload = function(e) {
		        preview.innerHTML = '<img src="' + e.target.result + '">';
		    }
		    reader.readAsDataURL(file);

		    preview.className = '';

		    var formData = new FormData();
		    formData.append('file', file);

		    var xhr = new XMLHttpRequest();
		    xhr.onload = function () {
		        try {
		        	var result = JSON.parse(this.responseText);
		        	if (result.ret === 0) {
		        		alert('上传成功，地址：' + location.protocol + '//demo.deanhan.cn/paste-upload/' + result.path);
		        	} else {
		        		alert('上传失败');
		        	}
		        } catch(e) {
		        	alert('上传失败');
		        }
		    };
		    xhr.onerror = function () {
		        alert('上传失败');
		    };
		    xhr.open('POST', './upload_file.php', true);
		    xhr.send(formData);
		});
	})();
</script>
</body>
</html>